package com.qqtech.qquan.im.controller;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.circle.enums.CircleApplyStatusDictEnum;
import com.qqtech.qquan.circle.enums.CircleInviteStatusDictEnum;
import com.qqtech.qquan.circle.model.CircleApplyQuery;
import com.qqtech.qquan.circle.model.CircleApplyVo;
import com.qqtech.qquan.circle.model.CircleBase;
import com.qqtech.qquan.circle.model.CircleInviteQuery;
import com.qqtech.qquan.circle.model.CircleInviteVo;
import com.qqtech.qquan.circle.model.CircleMemberVo;
import com.qqtech.qquan.circle.service.CircleApplyService;
import com.qqtech.qquan.circle.service.CircleBaseService;
import com.qqtech.qquan.circle.service.CircleInviteService;
import com.qqtech.qquan.circle.service.CircleMemberService;
import com.qqtech.qquan.im.model.ImGroupQuery;
import com.qqtech.qquan.im.model.ImMessage;
import com.qqtech.qquan.im.model.ImMessageQuery;
import com.qqtech.qquan.im.model.ImMessageVo;
import com.qqtech.qquan.im.model.ImUserQuery;
import com.qqtech.qquan.im.service.ImMessageService;
import com.qqtech.qquan.im.service.ImUserService;
import com.qqtech.qquan.pub.service.PubCommentService;
import com.qqtech.qquan.pub.service.PubPraiseService;
import com.qqtech.qquan.push.service.PushBizzService;
import com.qqtech.qquan.user.enums.UserFriendApplyStatusDictEnum;
import com.qqtech.qquan.user.model.UserBaseVo;
import com.qqtech.qquan.user.model.UserFriendApplyQuery;
import com.qqtech.qquan.user.model.UserFriendApplyVo;
import com.qqtech.qquan.user.service.UserBaseService;
import com.qqtech.qquan.user.service.UserFriendApplyService;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/im/message")
public class ImMessageController extends BaseWebController<ImMessage, ImMessageQuery> {
	@Resource
	private ImUserService imUserService;
	@Resource
	private ImMessageService imMessageService;
	@Resource
	private UserBaseService userBaseService;
	@Resource
	private PubPraiseService pubPraiseService;
	@Resource
	private PubCommentService pubCommentService;
	@Resource
	private CircleInviteService circleInviteService;
	@Resource
	private CircleApplyService circleApplyService;
	@Resource
	private UserFriendApplyService userFriendApplyService;
	@Resource
	private CircleMemberService circleMemberService;
	@Resource
	private PushBizzService pushBizzService;
	@Resource
	private CircleBaseService circleBaseService;

	@Override
	protected BaseService<ImMessage> getBaseService() {
		return imMessageService;
	}

	/**
	 * 查询我俩的聊天记录5天
	 * 
	 * @param imUserQ
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/getOurImMessage")
	@ResponseBody
	public Result getOurImMessage(@RequestBody ImUserQuery imUserQ) {
		Result result = new Result();
		long now = System.currentTimeMillis();
		long daysBefore = now - (3 * 24 * 60 * 60 * 1000);// 3天前
		if (imUserQ.getLastMsgTime() != null) {
			daysBefore = imUserQ.getLastMsgTime() + 10;// 往后加10毫秒
		}
		Integer userId = imUserQ.getUserId();
		Integer curUserId = this.getUserId();
		List<ImMessageVo> messageList = Lists.newArrayList();
		if (userId != null && curUserId != null) {
			messageList = imMessageService.get2UserMessages(curUserId, userId, new Timestamp(daysBefore));
		} else {
			result.addErr("用户信息userId为空");
			return result;
		}
		result.put("messageList", messageList);
		return result;
	}

	/**
	 * 查询一个群的聊天记录5天
	 * 
	 * @param imGroupQ
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/getGroupImMessage")
	@ResponseBody
	public Result getGroupImMessage(@RequestBody ImGroupQuery imGroupQ) {
		Result result = new Result();
		long now = System.currentTimeMillis();
		long daysBefore = now - (3 * 24 * 60 * 60 * 1000);// 3天前
		if (imGroupQ.getLastMsgTime() != null) {
			daysBefore = imGroupQ.getLastMsgTime() + 10;// 往后加10毫秒
		}
		Integer groupId = imGroupQ.getGroupId();
		Integer curUserId = super.getUserId();
		if (groupId == null) {
			result.addErr("群组groupId为空");
			return result;
		}
		CircleMemberVo circleMember = circleMemberService.getCircleMember(curUserId, groupId);
		if (circleMember != null) {
			long joinTime = circleMember.getNewAt().getTime();// 加入圈子的时间
			if (joinTime > daysBefore) {// 防止新用户加入圈子后看到之前的聊天记录
				daysBefore = joinTime;
			}
		}

		List<ImMessageVo> messageList = imMessageService.getGroupMessages(groupId, new Timestamp(daysBefore));
		result.put("messageList", messageList);
		return result;
	}

	// 消息页面--查询新的点赞、评论、好友申请、圈子邀请
	@RequestMapping(value = "/getOtherMessage")
	@ResponseBody
	public Result getOtherMessage(@RequestBody Map<String, String> map) {
		Result result = new Result();
		if (!super.isVisitor()) {
			Integer curUserId = super.getUserId();
			result.put("circleInviteList", myCircleInviteList(curUserId));
			result.put("friendApplyList", myFriendApplyList(curUserId));
			result.put("circleApplyList", myCircleApplyList(curUserId));
		}
		return result;
	}

	@RequestMapping(value = "/sendMsgToUser")
	@ResponseBody
	public Result sendMsgToUser(@RequestBody Map<String, String> map) {
		Result result = new Result();
		String herUserId = map.get("herUserId");
		if (StringUtil.isNotBlank(herUserId)) {
			pushBizzService.imNotifyWhenUserBg(new Integer(herUserId));
		}
		return result;
	}

	// 我收到的圈子邀请列表
	private List<CircleInviteVo> myCircleInviteList(Integer beUserId) {
		UserBaseVo userVo = null;// 用于取用户呢称、头像
		CircleInviteQuery circleInviteQ = new CircleInviteQuery();
		circleInviteQ.setBeInviterId(beUserId);// 我是被邀请人
		circleInviteQ.setStatus(CircleInviteStatusDictEnum.WAITING.getCode());

		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "newAt"));
		List<CircleInviteVo> inviteList = circleInviteService.queryList(circleInviteQ, pageKit);
		CircleBase circle = null;
		if (inviteList != null && inviteList.size() > 0) {
			for (CircleInviteVo inviteVo : inviteList) {
				userVo = userBaseService.getById(inviteVo.getInviterId());
				inviteVo.setInviterImg(userVo.getLogo());
				inviteVo.setInviterName(userVo.getNick());
				circle = circleBaseService.getById(inviteVo.getCircleId());
				if(circle!=null){
					inviteVo.setCircleName(circle.getName());
				}
			}
		}
		return inviteList;
	}

	// 我收到的圈子申请列表（有人申请加入我创建的圈子）
	private List<CircleApplyVo> myCircleApplyList(Integer beUserId) {
		UserBaseVo userVo = null;// 用于取用户呢称、头像
		CircleApplyQuery circleApplyQ = new CircleApplyQuery();
		Integer curUserId = super.getUserId();// 当前用户id
		circleApplyQ.setCircleOwnerId(curUserId);// 我是圈主
		circleApplyQ.setStatus(CircleApplyStatusDictEnum.WAITING.getCode());
		
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE,new PageOrder(Direction.DESC, "newAt"));
		List<CircleApplyVo> applyList = circleApplyService.queryList(circleApplyQ, pageKit);
		CircleBase circle = null;
		if (applyList != null && applyList.size() > 0) {
			for (CircleApplyVo applyVo : applyList) {
				userVo = userBaseService.getById(applyVo.getApplyerId());
				applyVo.setApplyerImg(userVo.getLogo());
				applyVo.setApplyerName(userVo.getNick());
				circle = circleBaseService.getById(applyVo.getCircleId());
				if(circle!=null){
					applyVo.setCircleName(circle.getName());
				}
			}
		}
		return applyList;
	}

	// 我收到的好友申请列表
	private List<UserFriendApplyVo> myFriendApplyList(Integer beUserId) {
		UserBaseVo userVo = null;// 用于取用户呢称、头像
		UserFriendApplyQuery friendApplyQ = new UserFriendApplyQuery();
		friendApplyQ.setFriendId(beUserId);// 我是被邀请人
		friendApplyQ.setStatus(UserFriendApplyStatusDictEnum.WAITING.getCode());

		Pageable pageKit = new PageKit(1,Integer.MAX_VALUE, new PageOrder(Direction.DESC, "newAt"));
		List<UserFriendApplyVo> applyList = userFriendApplyService.queryList(friendApplyQ, pageKit);
		if (applyList != null && applyList.size() > 0) {
			for (UserFriendApplyVo applyVo : applyList) {
				userVo = userBaseService.getById(applyVo.getUserId());
				applyVo.setUserLogo(userVo.getLogo());
				applyVo.setUserName(userVo.getNick());
			}
		}

		return applyList;
	}
}
